package com.piggy.system.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.piggy.common.core.constant.UserConstants;
import com.piggy.common.core.domain.R;
import com.piggy.common.core.utils.StringUtils;
import com.piggy.common.core.utils.poi.ExcelUtil;
import com.piggy.common.core.web.controller.BaseController;
import com.piggy.common.core.web.domain.AjaxResult;
import com.piggy.common.core.web.page.TableDataInfo;
import com.piggy.common.log.annotation.Log;
import com.piggy.common.log.enums.BusinessType;
import com.piggy.common.satoken.annotation.Inner;
import com.piggy.common.satoken.utils.SecurityUtils;
import com.piggy.oss.cloud.OSSFactory;
import com.piggy.system.api.domain.SysRole;
import com.piggy.system.api.domain.SysUser;
import com.piggy.system.api.model.LoginUser;
import com.piggy.system.enums.OrgTypeEnum;
import com.piggy.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户信息
 *
 * @author shark
 */
@RestController
@RequestMapping("/user")
public class SysUserController extends BaseController {
    @Autowired
    private ISysUserService userService;

    @Autowired
    private ISysRoleService roleService;

    @Autowired
    private ISysPostService postService;

    @Autowired
    private ISysPermissionService permissionService;

    @Autowired
    private ISysDeptService deptService;

    /**
     * 获取用户列表
     */
    @SaCheckPermission("system:user:list")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
        startPage();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @SaCheckPermission("system:user:export")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysUser user) throws IOException {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.exportExcel(response, list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @SaCheckPermission("system:user:import")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String operName = SecurityUtils.getUsername();
        String message = userService.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        util.importTemplateExcel(response, "用户数据");
    }

    /**
     * 获取当前用户信息
     */
    @Inner
    @GetMapping("/info/{username}")
    public R<LoginUser> info(@PathVariable("username") String username) {
        SysUser sysUser = userService.selectUserByUserName(username);
        if (StringUtils.isNull(sysUser)) {
            return R.fail("用户名或密码错误");
        }
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(sysUser.getUserId());
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(sysUser.getUserId());
        LoginUser sysUserVo = new LoginUser();
        sysUserVo.setSysUser(sysUser);
        sysUserVo.setRoles(roles);
        sysUserVo.setPermissions(permissions);
        return R.ok(sysUserVo);
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo() {
        Long userId = SecurityUtils.getUserId();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(userId);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(userId);
        Map<String, Object> ajax = new HashMap<>(3);
        SysUser user = userService.selectUserById(userId);
        String avatar = OSSFactory.build().buildUrl(user.getAvatar());
        user.setAvatar(avatar);
        ajax.put("user", user);
        ajax.put("roles", roles);
        if(SysUser.isAdmin(userId)){
            //999 超级管理员
            ajax.put("orgType",OrgTypeEnum.SYSADMIN.getCode());//返回给前端判断用
            ajax.put("orgTypeName","超级管理员");
        }else{
            Integer orgType=deptService.getOrgType(SecurityUtils.getDeptId(),"incar");
            if(orgType==null){
                //0 未知
                ajax.put("orgType", OrgTypeEnum.UNKNOWN.getCode());
                ajax.put("orgTypeName","未知");
            }else{
                ajax.put("orgType",orgType);
                if(OrgTypeEnum.CHESHANG.getCode().equals(orgType)){
                    ajax.put("orgDeptId",orgType);//1 车商  帮助那边需要返回这个
                    ajax.put("orgTypeName","车商");
                }else if(OrgTypeEnum.ZHONGWAIYUN.getCode().equals(orgType)){
                    ajax.put("orgDeptId",orgType);//2  中外运
                    ajax.put("orgTypeName","中外运");
                }else if(OrgTypeEnum.PLATFORM.getCode().equals(orgType)){
                    ajax.put("orgDeptId",orgType);//3  平台
                    ajax.put("orgTypeName","平台");
                }else if(OrgTypeEnum.BANK.getCode().equals(orgType)){
                    ajax.put("orgDeptId",orgType);//4  资方
                    ajax.put("orgTypeName","金融机构");
                }else if(OrgTypeEnum.OFFSHORE.getCode().equals(orgType)){
                    ajax.put("orgDeptId",orgType);//5  离岸公司
                    ajax.put("orgTypeName","离岸公司");
                }else{
                    ajax.put("orgTypeName","未知");
                }
            }

        }
        ajax.put("permissions", permissions);
        return AjaxResult.success(ajax);
    }

    /**
     * 根据用户编号获取详细信息
     */
    //@SaCheckPermission("system:user:query")
    @GetMapping(value = {"/", "/{userId}"})
    public R<SysUser> getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        /*Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put("user", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }*/
        if (Objects.isNull(userId)) {
            userId = SecurityUtils.getUserId();
        }
        return R.ok(userService.selectUserById(userId));
    }

    /**
     * 根据用户编号获取详细信息
     */
    //@SaCheckPermission("system:user:query")
    @GetMapping(value = {"infoById/", "infoById/{userId}"})
    public R<Map<String, Object>> getInfoById(@PathVariable(value = "userId", required = false) Long userId) {
        Map<String, Object> ajax = new HashMap<>();
        List<SysRole> roles = roleService.selectRoleAll();
        ajax.put("roles", SysUser.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put("user", userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return R.ok(ajax);
    }

    /**
     * 新增用户
     */
    @SaCheckPermission("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUsername());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return toAjax(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (StringUtils.isNotEmpty(user.getPhonenumber())
                && UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail())
                && UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return AjaxResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @SaCheckPermission("system:user:remove")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{userIds}")
    public AjaxResult remove(@PathVariable Long[] userIds) {
        return toAjax(userService.deleteUserByIds(userIds));
    }

    /**
     * 重置密码
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public AjaxResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @SaCheckPermission("system:user:edit")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(userService.updateUserStatus(user));
    }

    @Inner
    @GetMapping("/getUser/{deptId}")
    public R<List<SysUser>> getUserByDeptId(@PathVariable(value = "deptId", required = false) Long deptId) {
        return R.ok(userService.getUserByDeptId(deptId));
    }

    @Inner
    @GetMapping("/getUserByDeptIds")
    public R<List<SysUser>> getUserByDeptIds(@RequestParam("deptIds") List<Long> deptIds) {
        return R.ok(userService.getUserByDeptIds(deptIds));
    }

    @Inner
    @PostMapping("/queryUserAll")
    public R<List<SysUser>> queryUserAll() {
        return R.ok(userService.queryUserAll());
    }

    @Inner
    @GetMapping("/getUsersByPhoneNumber")
    public R<List<SysUser>> getUsersByPhoneNumber(@RequestParam("phoneNumber") String phoneNumber) {
        return R.ok(userService.getUsersByPhoneNumber(phoneNumber));
    }
    @Inner
    @GetMapping("/getUserByID")
    public R<SysUser> getUserByID(@RequestParam("userId") Long userId) {
        return R.ok(userService.getById(userId));
    }
}
